
const { SerialPort } = require('serialport')
const {ReadlineParser} = require('@serialport/parser-readline')
const { DelimiterParser } = require('@serialport/parser-delimiter')
const { ByteLengthParser } = require('@serialport/parser-byte-length')
// const iconv = require("iconv-lite");
const WebSocket  = require('ws')
const {uart1,uart4,uartZ,robot_type} = require('./config.js')
const {writeFileSync } = require('fs')

const WebSocketServer = WebSocket.Server;
const cell_sta = require('./BMS_bestway.js')

const wss =new WebSocketServer({ port:10088 },(err)=>{
	if(!err){
		console.log("Websocket Server启动运行了,监听端口 10088 .....")
	}
})

let portZ = false;
if(uartZ != undefined) portZ = true;

//如果有WebSocket请求接入，wss对象可以响应connection事件来处理这个WebSocket：
wss.on('connection',function(ws,req){  //在connection事件中，回调函数会传入一个WebSocket的实例，表示这个WebSocket连接。
    console.log(`[SERVER] connection()`);
	console.log(req.url)
	if(req.url.match(/m32_cmd/)){
		setup_m32_urt1_conn(ws)
	}
	
	if(req.url.match(/ins_data/)){
		setup_uart4_conn(ws)
	}
	
	if(req.url.match(/robot_arm/)){
		setup_uartZZ_conn(ws)
	}
	if(req.url.match(/conn_test/) && robot_type != undefined){
		ws.send(`-----current robot:${robot_type} ------------`)
	}
    
    if(req.url.match(/cell_status/)){
        setup_cellsta_conn(ws)
    }
})


function heartBeat(ws){
	this.isAlive = true
}

function setup_cellsta_conn(ws){
    ws.on('message',(data)=>{
        
    })
    
    const tmr = setInterval(()=>{
        ws.send(JSON.stringify( cell_sta))
    },10*1000)
    
    ws.on('close',()=>{
        clearInterval(tmr)
    })
}

//保存所有连接到uart1通道的客户端连接
const parser1_conn=[]
let  app_data = Buffer.alloc(0)
let  begin_save = false 
function setup_m32_urt1_conn(ws){
	console.log("Setup事件处理函数for new connection~~ ",ws.readyState)
	
	ws.on('message',(msg)=>{
		console.log(`[uart1 proxy] Received:`,msg.length,typeof msg);
        port1.write(msg)

	})
	
	ws.on('close',()=>{
		
	})
	
	ws.on('pong',heartBeat)
	
	ws.on('error',(err)=>{
		console.error(err,err.code)
	})
	
	ws.isAlive = true 
	
	parser1_conn.push(ws)
}


// 保存所有连接到Uart4通道的客户端连接
const parser2_conn = []


function setup_uart4_conn(ws){
    console.log("Setup事件处理函数for新连接~~ ",ws.readyState)
    
	ws.on('message',(msg)=>{
		console.log(`[Uart4 proxy] get Upsoft:`,msg.length,msg)
        port4.write(msg)
        
	})
	
    ws.on('close',()=>{
        
    })
    
    ws.on('pong',heartBeat)
    
    ws.on('error',(err)=>{
        console.error(err,err.code)
    })
    
    ws.isAlive = true 
    
    parser2_conn.push(ws)
}

const parserZZ_conn=[]
function setup_uartZZ_conn(ws){
	
    console.log("Setup事件处理函数for新x连接~~ ",ws.readyState)
    
	ws.on('message',(msg)=>{
		console.log(`[UartZZ proxy] get Upsoft:`,msg)
        portZZ.write(msg)
        
	})
	
    ws.on('close',()=>{
        
    })
    
    ws.on('pong',heartBeat)
    
    ws.on('error',(err)=>{
        console.error(err,err.code)
    })
    
    ws.isAlive = true 
    
    parserZZ_conn.push(ws)
	
}


const port1 = new SerialPort({ path: uart1.dev_name,
							baudRate: uart1.baud,
							autoOpen: true})
const port4 = new SerialPort({ path: uart4.dev_name,
							baudRate: uart4.baud,
							autoOpen: true})
							
let portZZ = null
if(portZ){
    portZZ = new SerialPort({ path: uartZ.dev_name,
							baudRate: uartZ.baud,
							autoOpen: true})
}

							
const parser1 = port1.pipe( new DelimiterParser({delimiter:'\r\n',includeDelimiter: true}) )
//port1.pipe(parser1)
const parser4 = port4.pipe( new DelimiterParser({delimiter:[0xfe,0xff],includeDelimiter: false}) )

let parserZ = null;
if(portZ){
    parserZ = portZZ.pipe( new ByteLengthParser({ length: 1 }) )
}



parser1.on('data',(response)=>{
	console.log("收到单片机串口1数据")
		
	parser1_conn.forEach((conn,index,arr)=>{
		if(conn && conn.readyState == 1){
			conn.send(response,(err)=>{
				if(err) console.error(`[uart1 proxy] Error:${err}`)
			})
		}
	})
})


let count = 0
parser4.on('data',(dd)=>{
    count ++
    if(count % 100 == 0){
        console.log("Get mcu_Uart4 data")
    }
    
    parser2_conn.forEach((ws,index,arr)=>{
        if(ws && ws.readyState==1){
            ws.send(dd,(err)=>{
                if(err)console.warn(`[Uart4 proxy] Transfer data Error:${err}`)
            })
        }
    })
})

const  doj_msg =[]
let remain = null
if(portZ){
    parserZ.on('data',(bb)=>{
        //console.log('看看bb是啥样',bb)
   
        doj_msg.push(bb[0])
     
        if(doj_msg.length>4 &&  doj_msg[3]>=3 && doj_msg[3]<10  && doj_msg.length==doj_msg[3]+3 ){
            const message = Buffer.from(doj_msg)
            parserZZ_conn.forEach((ws,index,arr)=>{
                if(ws && ws.readyState==1){
                    ws.send(message,(err)=>{
                         if(err)console.warn(`[UartZZ proxy] Transfer data Error:${err}`)
                    })
                }
            })
            doj_msg.length = 0
        }
        else if(doj_msg.length>4 && (doj_msg[3]<3 || doj_msg[3]>10)){
            console.warn('错误的舵机响应消息长度~ Len=%d',doj_msg[3])
            doj_msg.length = 0
        }
     
        if(doj_msg.length<=2 && doj_msg[0] != 0x55){
	        doj_msg.length = 0
        }
     
    })
}



let ccn = 0
const interval = setInterval(function ping() {
    if((++ccn) % 3 == 0){
        console.log(`wss.clients总共有${wss.clients.size}个连接`)
        console.log(`parser1_conn池总共有${parser1_conn.length}个连接`)
        console.log(`parser4_conn池子中有${parser2_conn.length}个连接`)
        console.log(`parserZZ_conn池子中有${parserZZ_conn.length}个连接`)
    }
    wss.clients.forEach(function each(ws) {
        if (ws.isAlive === false){
            let idx = parser1_conn.indexOf(ws)
            if(-1 != idx){
                parser1_conn[idx] = undefined
                ws.terminate();
                console.log("串口1上的客户端连接断掉一个@@@")
            }else{
                idx = parser2_conn.indexOf(ws)
                if(-1 != idx){
                    parser2_conn[idx] = undefined
                    ws.terminate()
                    console.log("串口4上的客户端会话减少一个~~~")
                }else{
                    idx = parserZZ_conn.indexOf(ws)
                    if(-1 != idx){
                        parserZZ_conn[idx] = undefined
                        ws.terminate()
                        console.log("串口ZZ 上的客户端会话减少一个~~~")
                    }
                }
            }
        }

        ws.isAlive = false;
        ws.ping();
    });
}, 6000);



